package com.framework.spring.domain;

import com.framework.spring.annotations.Autowired;
import com.framework.spring.annotations.Component;
import com.framework.spring.annotations.PostConstruct;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author duanzhizhou
 * @date 2025/4/8
 */
public class BeanDefinition {
    
    private final String name;
    
    private final List<Field> fields;
    
    private final Constructor<?> constructor;
    
    private final Method postContstruct;
    
    private final Class<?> type;
    
    public BeanDefinition(Class<?> type) {
        this.type = type;
        Component component = type.getAnnotation(Component.class);
        this.name = component.value().isEmpty() ? type.getSimpleName() : component.value();
        this.fields = Arrays.stream(type.getDeclaredFields()).filter(f -> f.isAnnotationPresent(Autowired.class)).collect(Collectors.toList());
        this.postContstruct = Arrays.stream(type.getDeclaredMethods()).filter(m -> m.isAnnotationPresent(PostConstruct.class)).findFirst().orElse(null);
        try {
            this.constructor = type.getConstructor();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
    
    public String getName() {
        return name;
    }
    
    public List<Field> getFields() {
        return fields;
    }
    
    public Constructor<?> getConstructor() {
        return constructor;
    }
    
    public Method getPostContstruct() {
        return postContstruct;
    }
    
    public Class<?> getType() {
        return type;
    }
}
